public class CityInventoryApprovalController
{
     public String RecordId
     {
           get
           {
               return String.valueOf(System.currentPageReference().getParameters().get('id')).substring(0,15);  
           }
           set;
     }
     public User CurrentUser
     {
         get
         {
             return [select id,Title__c from User where id=:UserInfo.getUserId()];
         }
     }
     public List<CheckInventoryItem__c> CheckItemList{get;set;}
     public CheckInventory__c CInventory{get;set;}
     public List<CityInventoryCheckApprovalEntry> CheckItemEntryList{get;set;}
     public Boolean IsDisplayForApproveButton{get;set;}
     public Boolean IsDisplayForRejectButton{get;set;}
     
    public CityInventoryApprovalController()
    {
        IsDisplayForApproveButton=true;
        IsDisplayForRejectButton=true;
        
        if(CheckItemEntryList==NULL)
            CheckItemEntryList=new List<CityInventoryCheckApprovalEntry>();
        else
            CheckItemEntryList.clear();
          //查出Check项
         CInventory=[select id,CheckDate__c,ProductName__c,CityName__c,ApprovalID__c from CheckInventory__c where id=:RecordId];
         //查出Check Item
         if(CurrentUser.Title__c=='Regional Sales Manager')
         {
             for(CheckInventoryItem__c cItem: [select id,Type__c,ReasonDescription__c,Unit__c,ApprovalDescription__c 
                                                                                    from CheckInventoryItem__c where CheckInventory__c=:RecordId and Approval_Stage__c='已提交'])
             {
                 CityInventoryCheckApprovalEntry entry=new CityInventoryCheckApprovalEntry(false,'待审批',cItem);
                 CheckItemEntryList.add(entry);
             }
         }
         else
         {
              for(CheckInventoryItem__c cItem: [select id,Type__c,ReasonDescription__c,Unit__c,ApprovalDescription__c 
                                                                                    from CheckInventoryItem__c 
                                                                                    where CheckInventory__c=:RecordId 
                                                                                    and Approval_Stage__c='RSM已审批'
                                                                                    and ApprovalRejectOrAgree__c='同意'])
             {
                 CityInventoryCheckApprovalEntry entry=new CityInventoryCheckApprovalEntry(false,'待审批',cItem);
                 CheckItemEntryList.add(entry);
             }
         }
    }
    public PageReference ApproveItems()
    {
        List<CheckInventoryItem__c> cItemList=new List<CheckInventoryItem__c>();
        for(CityInventoryCheckApprovalEntry entry:CheckItemEntryList)
        {
            if(entry.IsCheck &&  entry.ApprovalStatus=='待审批')
            {
                 entry.ApprovalStatus='已审批';
                 entry.ApprovedOrRejected='同意';
                CheckInventoryItem__c items=entry.CItem;
                if(CurrentUser.Title__c=='Regional Sales Manager')
                    items.Approval_Stage__c='RSM已审批';
                else
                    items.Approval_Stage__c='总部已审批';
                    
                items.ApprovalRejectOrAgree__c='同意';
                cItemList.add(items);
            }
        }
        update cItemList;
       if(ProcessApproval())
       {
            PageReference pr=new PageReference('/'+CInventory.Id);
            pr.setredirect(true);
            return pr;
       }
      /*  Approval.ProcessWorkitemRequest req2 = new Approval.ProcessWorkitemRequest();
        req2.setComments('同意');
        req2.setAction('Approve');
        req2.setWorkitemId(CInventory.ApprovalID__c);
        Approval.ProcessResult result2 =  Approval.process(req2);
        
         if(result2.getNewWorkitemIds()!=NULL && result2.getNewWorkitemIds().size()>0)
        {
           CInventory.ApprovalID__c=(String)result2.getNewWorkitemIds().get(0);
           update CInventory;
        }
         IsDisplayForApproveButton=false;*/
       
        return null;
    }
    public PageReference RejectItems()
    {
         List<CheckInventoryItem__c> cItemList=new List<CheckInventoryItem__c>();
        for(CityInventoryCheckApprovalEntry entry:CheckItemEntryList)
        {
            if(entry.IsCheck && entry.ApprovalStatus=='待审批')
            {
                 entry.ApprovalStatus='已审批';
                 entry.ApprovedOrRejected='拒绝';
                CheckInventoryItem__c items=entry.CItem;
                 if(CurrentUser.Title__c=='Regional Sales Manager')
                    items.Approval_Stage__c='RSM已审批';
                else
                    items.Approval_Stage__c='总部已审批';
              
                items.ApprovalRejectOrAgree__c='拒绝';
                cItemList.add(items);
            }
        }
        update cItemList;
        if(ProcessApproval())
        {
            PageReference pr=new PageReference('/'+CInventory.Id);
            pr.setredirect(true);
            return pr;
        }
       /* Boolean flag=true;
         for(CityInventoryCheckApprovalEntry entry:CheckItemEntryList)
         {
             if(entry.ApprovedOrRejected=='同意' || entry.ApprovedOrRejected==NULL)
                 flag=false;
         }
      
        //如果全部拒绝时则触发审批流
        if(flag)
        {
             //   system.assert(false,CheckItemEntryList);
                Approval.ProcessWorkitemRequest req2 = new Approval.ProcessWorkitemRequest();
                req2.setComments('拒绝');
                req2.setAction('Reject');
                req2.setWorkitemId(CInventory.ApprovalID__c);
                Approval.ProcessResult result2 =  Approval.process(req2);
        }
       
         IsDisplayForRejectButton=false;*/
        return null;
    }
    public boolean ProcessApproval()
    {
        Boolean statusFlag=true,rejectFlag=true;
         for(CityInventoryCheckApprovalEntry entry:CheckItemEntryList)
         {
             if(entry.ApprovalStatus=='待审批')
                 statusFlag=false;
         }
         if(statusFlag)//如果全部审批
         {
             for(CityInventoryCheckApprovalEntry entry:CheckItemEntryList)
             {
                 if(entry.ApprovedOrRejected=='同意')
                    rejectFlag=false;
             }
             if(rejectFlag)//拒绝
             {
                    Approval.ProcessWorkitemRequest req2 = new Approval.ProcessWorkitemRequest();
                    req2.setComments('拒绝');
                    req2.setAction('Reject');
                    req2.setWorkitemId(CInventory.ApprovalID__c);
                    Approval.ProcessResult result2 =  Approval.process(req2);
                    return true;
             }
             else//同意
             {
                 Approval.ProcessWorkitemRequest req2 = new Approval.ProcessWorkitemRequest();
                req2.setComments('同意');
                req2.setAction('Approve');
                req2.setWorkitemId(CInventory.ApprovalID__c);
                Approval.ProcessResult result2 =  Approval.process(req2);
                
                 if(result2.getNewWorkitemIds()!=NULL && result2.getNewWorkitemIds().size()>0)
                {
                   CInventory.ApprovalID__c=(String)result2.getNewWorkitemIds().get(0);
                   update CInventory;
                }
                
                //判断是否有部分拒绝，如果有则发邮件
                
                return true;
             }
         }
         return false;
    }
    //拒绝时发送邮件
    public void SendEmailToCheckInventoryOwner()
    {
        boolean isSend=false;
         for(CityInventoryCheckApprovalEntry entry:CheckItemEntryList)
         {
               if(entry.ApprovedOrRejected=='拒绝')
                    isSend=true;
         }
         if(isSend)
         {
             User u=[select Email from User where id=:UserInfo.getUserId()];
             String BodyString='您好！您提交的库存盘点信息部分已被拒绝，详情请登陆凤凰系统查看详情，谢谢！';
            String subject='库存盘点部分被拒绝';
            EmailHander.SendMail(BodyString,new String[]{u.Email},subject,'',null);
         }
    }
 }